Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Inheritance Concept

Extend keyword

In Java’s Object-Oriented Programming (OOP), the extends keyword is used to establish an inheritance relationship between two classes. The class that is being extended is known as the superclass or parent class, and the class that extends the superclass is known as the subclass or child class. Here’s the syntax for extending a class in Java:
Syntax to extend the class class SubClass extends SuperClass { // fields and methods }
In this syntax, SubClass is the class that is extending SuperClass. This means that SubClass inherits all the non-private members (fields and methods) of SuperClass. Here’s an example of extending a class in Java:
Example of extending a class in java inheritance // Superclass class Animal { void eat() { System.out.println("Animal is eating..."); } } // Subclass class Dog extends Animal { void bark() { System.out.println("Dog is barking..."); } } public class Test { public static void main(String args[]) { Dog d = new Dog(); d.bark(); d.eat(); } }

Output

Dog is barking... Animal is eating...
In this example, Dog is a subclass that extends the Animal superclass. The Dog class inherits the eat() method from the Animal class, and it also defines its own method bark(). In the main method, an object d of type Dog is created. This object can call both the bark() method and the eat() method. It’s important to note that Java does not support multiple inheritance through class. This means a class cannot extend more than one class. However, a class can implement multiple interfaces, which can achieve similar functionality.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ inheritance ★ inheritance example ★extends

Tutorials